<?php
/**
 * SocialEngine
 *
 * @category   Application_Extensions
 * @package    Like
 * @copyright  Copyright Hire-Experts LLC
 * @license    http://www.hire-experts.com
 * @version    $Id: Core.php 2010-09-07 16:05 idris $
 * @author     Idris
 */

/**
 * @category   Application_Extensions
 * @package    Like
 * @copyright  Copyright Hire-Experts LLC
 * @license    http://www.hire-experts.com
 */

class Like_Plugin_Core
{
  public function onRenderLayoutDefault($event)
  {
    // Arg should be an instance of Zend_View
    $view = $event->getPayload();
    $viewer = Engine_Api::_()->user()->getViewer();

    if( $view instanceof Zend_View && $viewer->getIdentity() && Engine_Api::_()->core()->hasSubject() ){
      $subject = Engine_Api::_()->core()->getSubject();
      $like_url = Zend_Controller_Front::getInstance()->getRouter()->assemble(array(
        'action' => 'like',
        'object' => $subject->getType(),
        'object_id' => $subject->getIdentity()
      ), 'like_default');

      $unlike_url = Zend_Controller_Front::getInstance()->getRouter()->assemble(array(
        'action' => 'unlike',
        'object' => $subject->getType(),
        'object_id' => $subject->getIdentity()
      ), 'like_default');
      
      $script = "window.addEvent('domready', function(){
        like.like_url = '" . $like_url . "';
        like.unlike_url = '" . $unlike_url . "';
        like.init();
      });";
      
      $view->headScript()
        ->appendFile('application/modules/Like/externals/scripts/core.js')
        ->appendScript($script);

      $view->headTranslate(array(
        'like_You', 'like_and', 'like_people', 'like_like it', 'like_Suggest to Friends', 'like_Unlike', 'like_Are you sure you want to unlike this?', 'like_Show Like', 'like_Hide', 'like_Like'
      ));
    }
  }
  
  public function onUserDeleteBefore($event)
  {
    $payload = $event->getPayload();
    if ( $payload instanceof User_Model_User ){
      $table = Engine_Api::_()->getDbTable('clubs', 'like');
      $select = $table->select()->where('user_id = ?', $payload->getIdentity());
      foreach ( $table->fetchAll($select) as $like_club ){
        $like_club->delete();
      }
      $table = Engine_Api::_()->getDbTable('likes', 'like');
      $table->delete("user_id = {$payload->getIdentity()}");
    }
  }
}